package io.keen.client.java.http;

import io.keen.client.java.KeenUtils;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;

public class UrlConnectionHttpHandler implements HttpHandler {
    public Response execute(Request request) throws IOException {
        HttpURLConnection connection = openConnection(request);
        sendRequest(connection, request);
        return readResponse(connection);
    }

    protected HttpURLConnection openConnection(Request request) throws IOException {
        HttpURLConnection result;
        if (request.proxy != null) {
            result = (HttpURLConnection) request.url.openConnection(request.proxy);
        } else {
            result = (HttpURLConnection) request.url.openConnection();
        }
        result.setConnectTimeout(30000);
        result.setReadTimeout(30000);
        return result;
    }

    protected void sendRequest(HttpURLConnection connection, Request request) throws IOException {
        connection.setRequestMethod(request.method);
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Authorization", request.authorization);
        if (request.body != null) {
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/json");
            request.body.writeTo(connection.getOutputStream());
            return;
        }
        connection.connect();
    }

    protected Response readResponse(HttpURLConnection connection) throws IOException {
        InputStream in;
        try {
            in = connection.getInputStream();
        } catch (IOException e) {
            in = connection.getErrorStream();
        }
        String body = "";
        if (in != null) {
            try {
                body = KeenUtils.convertStreamToString(in);
            } finally {
                KeenUtils.closeQuietly(in);
            }
        }
        return new Response(connection.getResponseCode(), body);
    }
}
